<template>
  <div class="app-layout">
    <header class="app-header" :class="{ 'no-header-border': isHome }">
      <div class="logo">FAMES 管理端</div>
      <el-button
        class="aside-toggle"
        text
        :icon="isAsideCollapsed ? Expand : Fold"
        @click="toggleAside"
        title="折叠/展开侧栏"
      />
      <div class="spacer" v-if="!isHome"></div>
      <!-- 主页中间区域显示标签切换 -->
      <div v-if="isHome" class="header-tabs">
        <el-tabs v-model="homeTab">
          <el-tab-pane label="系统介绍" name="intro" />
          <el-tab-pane label="节庆活动介绍" name="festival" />
        </el-tabs>
      </div>
      <div class="spacer"></div>
      <!-- 右侧：未登录显示登录按钮；已登录显示用户头像下拉 -->
      <div v-if="!auth.user" class="user">
        <el-button type="primary" @click="goLogin">登录</el-button>
      </div>
      <div v-else class="user">
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-avatar size="small" style="margin-right:8px">{{ auth.user.username?.charAt(0).toUpperCase() }}</el-avatar>
            {{ auth.user.username }}
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="goProfile">个人信息</el-dropdown-item>
              <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <div class="main-layout">
      <!-- 桌面侧栏：非登录/非首页且未折叠，且非移动端显示 -->
      <aside v-if="!isLogin && !isHome && !isAsideCollapsed && !isMobile" class="app-aside">
        <el-menu :default-active="active" class="el-menu-vertical" @select="onSelect">
          <template v-for="item in menuList" :key="item.path">
            <el-sub-menu v-if="item.children?.length" :index="item.path">
              <template #title>
                <el-icon v-if="item.icon" :size="16" style="margin-right: 8px;">
                  <component :is="getIconComponent(item.icon)" />
                </el-icon>
                {{ item.name }}
              </template>
              <el-menu-item v-for="c in item.children" :index="c.path" :key="c.path">
                <el-icon v-if="c.icon" :size="14" style="margin-right: 8px;">
                  <component :is="getIconComponent(c.icon)" />
                </el-icon>
                {{ c.name }}
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item v-else :index="item.path">
              <el-icon v-if="item.icon" :size="16" style="margin-right: 8px;">
                <component :is="getIconComponent(item.icon)" />
              </el-icon>
              {{ item.name }}
            </el-menu-item>
          </template>
        </el-menu>
      </aside>

      <!-- 移动端抽屉侧栏 -->
      <el-drawer
        v-if="isMobile"
        v-model="showMobileAside"
        direction="ltr"
        :with-header="false"
        size="240px"
        class="mobile-aside"
      >
        <el-menu :default-active="active" class="el-menu-vertical" @select="onSelect">
          <template v-for="item in menuList" :key="item.path">
            <el-sub-menu v-if="item.children?.length" :index="item.path">
              <template #title>
                <el-icon v-if="item.icon" :size="16" style="margin-right: 8px;">
                  <component :is="getIconComponent(item.icon)" />
                </el-icon>
                {{ item.name }}
              </template>
              <el-menu-item v-for="c in item.children" :index="c.path" :key="c.path">
                <el-icon v-if="c.icon" :size="14" style="margin-right: 8px;">
                  <component :is="getIconComponent(c.icon)" />
                </el-icon>
                {{ c.name }}
              </el-menu-item>
            </el-sub-menu>
            <el-menu-item v-else :index="item.path">
              <el-icon v-if="item.icon" :size="16" style="margin-right: 8px;">
                <component :is="getIconComponent(item.icon)" />
              </el-icon>
              {{ item.name }}
            </el-menu-item>
          </template>
        </el-menu>
      </el-drawer>

      <main class="app-main">
        <div class="content-card">
          <router-view />
        </div>
      </main>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, defineAsyncComponent } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from './store/auth'
import { useMenuStore } from './store/menu'
import { Fold, Expand } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const menuStore = useMenuStore()
const active = computed(() => route.path)
function onSelect(index: string) {
  router.push(index)
  if (isMobile.value) {
    showMobileAside.value = false
  }
}

const isLogin = computed(() => route.path === '/login')
const isHome = computed(() => route.path === '/home')

// 侧栏折叠与移动端状态
const isAsideCollapsed = ref(false)
const isMobile = ref(false)
const showMobileAside = ref(false)
function toggleAside() {
  if (isMobile.value) {
    showMobileAside.value = !showMobileAside.value
  } else {
    isAsideCollapsed.value = !isAsideCollapsed.value
  }
}
function updateIsMobile() {
  isMobile.value = window.innerWidth < 768
}

// 主页标签：使用路由query进行同步
const homeTab = computed({
  get: () => (typeof route.query.tab === 'string' ? route.query.tab : 'intro'),
  set: (val: string) => router.push({ path: '/home', query: { tab: val } }),
})

// Fallback菜单：在尚未配置角色菜单时显示基本导航
const fallbackMenus = [
  { name: '首页', path: '/home' },
  { name: '概览', path: '/admin/dashboard' },
  { name: '活动管理', path: '/admin/activity-mgmt', children: [
    { name: '活动', path: '/admin/activities' },
    { name: '事件', path: '/admin/events' },
  ]},
  { name: '指标管理', path: '/admin/indicator-mgmt', children: [
    { name: '指标', path: '/admin/indicators' },
  ]},
  { name: '评估管理', path: '/admin/evaluation-mgmt', children: [
    { name: '评估模版', path: '/admin/evaluation-templates' },
    { name: '大模型配置', path: '/admin/llm-config' },
    { name: '评估', path: '/admin/evaluations' },
    { name: '活动评分', path: '/admin/activity-scoring' },
  ]},
  { name: '系统管理', path: '/admin', children: [
    { name: '用户管理', path: '/admin/users' },
    { name: '角色管理', path: '/admin/roles' },
    { name: '菜单管理', path: '/admin/menus' },
    { name: '数据字典管理', path: '/admin/dictionaries' },
  ]},
]

const menuList = computed(() => {
  return (menuStore.uiTree && menuStore.uiTree.length > 0) ? menuStore.uiTree : fallbackMenus
})

onMounted(async () => {
  updateIsMobile()
  window.addEventListener('resize', updateIsMobile)
  if (auth.token) {
    try { await auth.fetchMe() } catch {}
    if (!isLogin.value) {
      try { await menuStore.loadTree() } catch {}
    }
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', updateIsMobile)
})

function logout() {
  auth.logout()
}

function goProfile() {
  router.push('/profile')
}

function goLogin() {
  router.push('/login')
}

// 获取图标组件
function getIconComponent(iconName: string) {
  if (!iconName) return null
  return defineAsyncComponent(() => 
    import('@element-plus/icons-vue').then(module => {
      if (module[iconName as keyof typeof module]) {
        return module[iconName as keyof typeof module]
      }
      // 如果Element Plus中没有，尝试从Lucide图标库导入
      return import('lucide-vue-next').then(lucideModule => {
        return lucideModule[iconName as keyof typeof lucideModule] || null
      })
    }).catch(() => {
      return null
    })
  )
}
</script>

<style>
/* 主题变量与基础色 */
:root {
  --accent: #4c8bf5;
  --bg-header: #ffffff;
  --bg-aside: #f7f9fc;
  --bg-main: #fbfcfe;
  --border-soft: #e9edf3;
  --text-primary: #1f2328;
  --text-muted: #6b7280;
}

* {
  box-sizing: border-box;
}

html, body { 
  margin: 0; 
  padding: 0;
  color: var(--text-primary); 
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

#app {
  height: 100vh;
  width: 100vw;
  overflow: hidden;
}

.app-layout {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 头部导航 */
.app-header {
  display: flex;
  align-items: center;
  height: 56px;
  padding: 0 20px;
  background: var(--bg-header);
  border-bottom: 1px solid var(--border-soft);
  flex-shrink: 0;
  z-index: 100;
}
.no-header-border { border-bottom: none; }
.logo { font-weight: 600; font-size: 18px; color: var(--text-primary); }
.aside-toggle { margin-left: 12px; }
.spacer { flex: 1; }
.header-tabs :deep(.el-tabs__item.is-active) { color: var(--accent); }
.header-tabs :deep(.el-tabs__nav) { justify-content: flex-start; }
.header-tabs { display: flex; align-items: center; }
.header-tabs :deep(.el-tabs__header) { margin: 0; border-bottom: none; }
.header-tabs :deep(.el-tabs__nav-wrap::after) { display: none; }
.header-tabs :deep(.el-tabs__active-bar) { display: none; }
.header-tabs :deep(.el-tabs__item) { height: 56px; line-height: 56px; }

/* 主布局区域 */
.main-layout {
  flex: 1;
  display: flex;
  overflow: hidden;
  height: calc(100vh - 56px);
}

/* 左侧导航 */
.app-aside {
  background: var(--bg-aside);
  border-right: 1px solid var(--border-soft);
  width: 240px;
  height: 100%;
  overflow-y: auto;
  flex-shrink: 0;
}
.el-menu-vertical {
  --el-menu-bg-color: var(--bg-aside);
  --el-menu-text-color: var(--text-muted);
  --el-menu-active-color: var(--accent);
  --el-menu-hover-bg-color: #eef4ff;
  border-right: none;
}
.el-menu-vertical :deep(.el-sub-menu__title) {
  font-weight: 600;
  color: var(--text-primary);
}
.el-menu-vertical :deep(.el-menu-item.is-active) {
  background: #eef4ff;
  color: var(--accent);
  border-left: 3px solid var(--accent);
}

/* 主内容区 */
.app-main { 
  background: var(--bg-main); 
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.content-card {
  background: #fff;
  border: 1px solid var(--border-soft);
  flex: 1;
  padding: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

/* 移动端抽屉样式 */
.mobile-aside :deep(.el-drawer__body) {
  padding: 0;
  background: var(--bg-aside);
}

/* 响应式：小屏下减少外边距 */
@media (max-width: 768px) {
  .app-main { padding: 12px; }
  .content-card { border-radius: 10px; padding: 12px; }
}
</style>
